package com.dc.web.controller;


import com.dc.constant.Constants;
import com.dc.constant.MessageConstant;
import com.dc.dao.*;
import com.dc.dao.vo.ShipAndRepairVO;
import com.dc.entity.*;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.ShipListSearchBody;
import com.dc.model.ShipRepairAddBody;
import com.dc.model.ShipRepairSearchBody;
import com.dc.service.UserService;
import com.dc.service.WorkflowService;
import com.dc.service.WorkflowStatService;
import com.dc.service.dto.WorkflowTowShipOilDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/ship_repair")
@Slf4j
public class ShipRepairController {

    @Resource
    private ShipRepairDao shipRepairDao;

    @Resource
    private UserService userService;

    @Resource
    private ShipAndRepairDao shipAndRepairDao;

    @Resource
    private WorkflowService workflowService;

    @Resource
    private ShipDao shipDao;

    @Resource
    private WorkflowStatService workflowStatService;

    @Resource
    WorkflowTopFirstDao workflowTopFirstDao;

    @Resource
    WorkflowTopSecondDao workflowTopSecondDao;

    @Resource
    WorkflowTopThirdDao workflowTopThirdDao;

    /**
     * 根据 船id和年度 来展示船维修列表
     * @param
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(ShipRepairSearchBody shipRepairSearchBody) {

        Integer pageNumber = shipRepairSearchBody.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = shipRepairSearchBody.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Date enterTimeBegin = shipRepairSearchBody.getEnterTimeBegin();
        Date enterTimeEnd = shipRepairSearchBody.getEnterTimeEnd();

        Long shipId = shipRepairSearchBody.getShipId();

        Integer complete = shipRepairSearchBody.getComplete();

        Page<ShipAndRepairVO> page = null;

        if(ObjectUtils.isEmpty(enterTimeBegin) && ObjectUtils.isEmpty(enterTimeEnd)  && ObjectUtils.isEmpty(shipId)) {
            page = shipAndRepairDao.findShipAndRepairVO(pageRequest);

        } else if(ObjectUtils.isEmpty(enterTimeBegin) && ObjectUtils.isEmpty(enterTimeEnd)) {
            page = shipAndRepairDao.findShipAndRepairVOByShipId(shipId, pageRequest);
        } else if(ObjectUtils.isEmpty(enterTimeBegin) && ObjectUtils.isEmpty(shipId)) {
            page = shipAndRepairDao.findShipAndRepairVOByEnterTimeEnd(enterTimeEnd, pageRequest);
        } else if(ObjectUtils.isEmpty(enterTimeEnd) && ObjectUtils.isEmpty(shipId)) {
            page = shipAndRepairDao.findShipAndRepairVOByEnterTimeBegin(enterTimeBegin, pageRequest);

        } else if(ObjectUtils.isEmpty(enterTimeBegin)) {
            page = shipAndRepairDao.findShipAndRepairVOByEnterTimeEndAndId(enterTimeEnd, shipId, pageRequest);
        } else if(ObjectUtils.isEmpty(shipId)) {
            page = shipAndRepairDao.findShipAndRepairVOByEnterTimeBeginAndEnterTimeEnd(enterTimeBegin, enterTimeEnd, pageRequest);
        } else if(ObjectUtils.isEmpty(enterTimeEnd)) {
            page = shipAndRepairDao.findShipAndRepairVOByEnterTimeBeginAndId(enterTimeBegin, shipId, pageRequest);
        } else {
            page = shipAndRepairDao.findShipAndRepairVOByEnterTimeBeginAndEnterTimeEndAndId(enterTimeBegin, enterTimeEnd, shipId, pageRequest);
        }

        Page<ShipAndRepairVO> result = page;
        // 不为空，则过滤
        if(ObjectUtils.isNotEmpty(complete)) {
            List<ShipAndRepairVO> collect = page.stream().filter(t -> Objects.equals(t.getComplete(), complete)).collect(Collectors.toList());
            int begin= (int) pageRequest.getOffset();
            int en= Math.min((begin + pageRequest.getPageSize()), collect.size());

            result = new PageImpl<ShipAndRepairVO>(collect.subList(begin,en),pageRequest,collect.size());

        }

        return AjaxResult.success(result);

    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<ShipRepairEntity> optional = shipRepairDao.findById(id);

        ShipRepairEntity shipRepairEntity = null;

        if(optional.isPresent()) {
            shipRepairEntity = optional.get();
        }

        return AjaxResult.success(shipRepairEntity);
    }

    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody ShipRepairAddBody body) {

        ShipRepairEntity entity = new ShipRepairEntity();
        entity.setCode(body.getCode());
        entity.setManager(body.getManager());
        entity.setManagerTel(body.getManagerTel());
        entity.setWorkFlows(StringUtils.join(body.getWorkFlows(), ","));
        entity.setEnterTime(body.getEnterTime());
        entity.setStartTime(body.getStartTime());
        entity.setEndTime(body.getEndTime());
        entity.setOutTime(body.getOutTime());
        entity.setShipId(body.getShipId());
        entity.setComplete(Constants.SHIP_REPAIR_STAT_NOT_COMPLETE);

        UserEntity user = userService.getUser(httpHeaders);

        entity.setUpdater(user.getUserName());

        ShipRepairEntity save = shipRepairDao.save(entity);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@RequestHeader HttpHeaders httpHeaders, @PathVariable("id") Long id, @RequestBody ShipRepairAddBody body) {

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(id);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity entity = optionalShipRepair.get();

        if(Constants.SHIP_REPAIR_STAT_COMPLETE.equals(entity.getComplete())) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MODIFIED);
        }

        List<String> workflowListForm = body.getWorkFlows();

        String workFlowsDB = entity.getWorkFlows();

        List<String> workFlowsListDB = Arrays.stream(workFlowsDB.split(",")).map(String::trim).collect(Collectors.toList());
        for(String workDB : workFlowsListDB) {
            int i = workflowListForm.indexOf(workDB);
            if(i == -1) {           // 编辑减少了工序，如果有数据，则报错
                List workflows = workflowService.getWorkflows(workDB, id);
                int size = workflows.size();
                if(size > 0) {
                    String format = String.format(MessageConstant.ERR_WORK_FLOW_CANT_DELETE, workDB);
                    throw new ServiceException(format);
                }
            }

        }
        entity.setCode(body.getCode());
        entity.setManager(body.getManager());
        entity.setManagerTel(body.getManagerTel());
        entity.setWorkFlows(StringUtils.join(body.getWorkFlows(), ","));
        entity.setEnterTime(body.getEnterTime());
        entity.setStartTime(body.getStartTime());
        entity.setEndTime(body.getEndTime());
        entity.setOutTime(body.getOutTime());
        entity.setShipId(body.getShipId());

        UserEntity user = userService.getUser(httpHeaders);

        entity.setId(id);
        entity.setUpdater(user.getUserName());

        ShipRepairEntity save = shipRepairDao.save(entity);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(id);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity entity = optionalShipRepair.get();

        if(Constants.SHIP_REPAIR_STAT_COMPLETE.equals(entity.getComplete())) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MODIFIED);
        }

        shipRepairDao.deleteById(id);

        return AjaxResult.success();
    }

    @GetMapping("/dict")
    public AjaxResult dict() {

        List<Map<String, Object>> result = new ArrayList<>();

        List<ShipRepairEntity> allRepairs = shipRepairDao.findAll();
        if(ObjectUtils.isEmpty(allRepairs)) {
            return AjaxResult.success(result);
        }

//        List<ShipEntity> allShips = shipDao.findAll();
//        if(ObjectUtils.isEmpty(allShips)) {
//            return AjaxResult.success(result);
//        }

        for(ShipRepairEntity repairEntity : allRepairs) {
            Long shipId = repairEntity.getShipId();
            String shipName = "默认";
            Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
            if(optionalShip.isPresent()) {
                shipName = optionalShip.get().getName();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("repairId", repairEntity.getId());
            map.put("shipId", shipId);
            map.put("shipName", shipName);
            map.put("enterTime", repairEntity.getEnterTime());
            map.put("startTime", repairEntity.getStartTime());
            map.put("endTime", repairEntity.getEndTime());
            map.put("outTime", repairEntity.getOutTime());
            map.put("code", repairEntity.getCode());
            map.put("workFlows", repairEntity.getWorkFlows());

            result.add(map);
        }

        return AjaxResult.success(result);
    }

    @PutMapping("/complete/{id}")
    public AjaxResult complete(@PathVariable("id") Long shipRepairId) {
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }
        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Integer complete = shipRepairEntity.getComplete();
        if(Constants.SHIP_REPAIR_STAT_COMPLETE.equals(complete)) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_FINISH);
        }

        Optional<ShipEntity> optionalShip = shipDao.findById(shipRepairEntity.getShipId());
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }
        ShipEntity shipEntity = optionalShip.get();

        /// 维修单竣工，写入 一二三级数据
        List<WorkflowTopThirdEntity> topThird = workflowStatService.getTopThird(shipEntity, shipRepairEntity);

        workflowTopThirdDao.saveAll(topThird);


        List<WorkflowTopSecondEntity> topSecond = workflowStatService.getTopSecond(shipEntity, shipRepairEntity);

        workflowTopSecondDao.saveAll(topSecond);

        List<WorkflowTopFirstEntity> topFirst = workflowStatService.getTopFirst(shipEntity, shipRepairEntity);

        workflowTopFirstDao.saveAll(topFirst);

        // 修改竣工状态
        shipRepairEntity.setComplete(Constants.SHIP_REPAIR_STAT_COMPLETE);
        ShipRepairEntity save = shipRepairDao.save(shipRepairEntity);


        return AjaxResult.success(save);
    }
}
